const express = require("express")
const router = express.Router()

const sqlQuery = require("../mysql/index.cjs")



function URL(arr){
  let url = []
  for (let index = 0; index < arr.length; index++) {
    let el = arr[index];
    let path = "http://127.0.0.1:8081/"
    url.push(path+el)
  }
  return url
}

// 首页
router.get("/home",(req,res)=>{
  console.log("查询首页");
  let sql = "select * from note"
  sqlQuery(sql, (msg)=>{
    // console.log(msg);
    let list = msg;
    if(list.length==0){
      res.send({
        status : 100,
        msg : "没有数据",
        data:[]
      })
    }
    let notes = []
    list.forEach(el => {
      let sql = `select * from user where id=${el.user_id}`
      sqlQuery(sql,msg => {
        let { id, url, title, content, comment_num, support_num, time,user_id } = el
        url = URL(JSON.parse(url))
        let {name, signature, avatar, sex, } = msg[0]
        let note = {
          id, url, title, content, comment_num, support_num, time,
          name, signature, avatar, sex,user_id
        }
        notes.push(note)
        if(list.length==notes.length){
          res.send({
            status:100,
            msg:"成功",
            data:notes
          })
        }
      })
    });
  })
})


module.exports = router